<template>
  <div class="app-container">
    <div class="manage-header">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="primary" @click="handleImport">导入</el-button>
      <el-button type="primary" @click="handleExport">导出</el-button>
    </div>
    <el-dialog
      title="导入Excel"
      :visible.sync="ImportDialog"
      width="30%"
      :before-close="handleClose"
    >
      <div
        style="margin-top: 30%"
      >
        <el-upload
          ref="upload"
          class="upload-demo"
          :action="actionAddress"
          :auto-upload="false"
          :on-success="handlemessage"
          style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器
          </el-button>
          <div slot="tip" class="el-upload__tip">请上传想要导入的Excel文件</div>
        </el-upload>
      </div>
    </el-dialog>
    <el-dialog
      title="导出Excel"
      :visible.sync="ExportDialog"
      width="30%"
      :before-close="handleClose"
    >
      <div style="float: top">
        <div
          style="position:relative;top:10%;bottom:0;left: 0;
            margin: auto;right: 0;
            text-align:center"
        >
          <el-button type="primary" @click="handleExport1">导出所有数据</el-button>
          <el-button type="primary" @click="handleExport2">导出模板</el-button>
        </div>
        <div width="100%">
          <h3 style="text-align: center">你可以选择“导出模板”导出一张空白Excel</h3>
        </div>
      </div>
    </el-dialog>
    <el-table
      stripe
      border
      height="450"
      :data="tableData"
      style="width: 100%"
      :header-cell-style="{'text-align': 'center'}"
    >
      <el-table-column
        prop="role"
        label="角色符号"
        align="center"
        width="200"
      />
      <el-table-column
        prop="roleName"
        label="角色名称"
        align="center"
        width="200"
      />
      <el-table-column
        prop="roleDesc"
        label="角色描述"
        align="center"
      />
      <el-table-column
        prop="addr"
        label="操作"
        align="center"
        width="200"
      >
        <template v-slot="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
      <el-dialog
        title="角色表单"
        :visible.sync="dialogVisible"
        center
        width="40%"
        :before-close="handleClose"
      >
        <!-- 角色的表单信息 -->
        <el-form ref="form" :rules="rules" :model="form" label-position="left" label-width="100px">
          <el-form-item prop="role" label="角色符号" style="width:200px;">
            <el-input v-model="form.role" placeholder="请输入角色符号" style="width: 200px" />
          </el-form-item>
          <el-form-item prop="roleName" label="角色名称" style="width:200px">
            <el-input v-model="form.roleName" placeholder="请输入角色名称" style="width: 200px" />
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述" style="width:200px">
            <el-input v-model="form.roleDesc" placeholder="请输入角色描述" type="textarea" style="width: 300px" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  roleinfo,
  add,
  update,
  deleteRole
} from '@/api/rolemanage'
import axios from 'axios'

export default {
  data() {
    return {
      total: 1,
      pageSize: 1,
      isShow: false,
      isShow1: false,
      dialogVisible: false,
      ImportDialog: false,
      ExportDialog: false,
      actionAddress: process.env.VUE_APP_BASE_API + '/RoleManage/import',
      currentPage: 1,
      tableData: [],
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      form: {
        role: '',
        roleName: '',
        roleDesc: ''
      },
      rules: {
        role: [
          { required: true, message: '请输入角色符号', trigger: 'blur' }
        ],
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      roleinfo().then(({ data }) => {
        this.total = data.page.total
        this.pageSize = data.page.size
        this.tableData = data.page.records
        this.isShow = true
        this.isShow1 = false
      })
    },
    handleAdd() {
      if (this.form.role !== '') {
        this.$refs.form.resetFields()
      }
      this.modalType = 0
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.modalType = 1
      this.dialogVisible = true
      this.$nextTick(function() {
        this.form = Object.assign(this.form, row)
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该角色信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(row.role).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 重新获取列表的接口
          this.handleCurrentChange(this.currentPage)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCurrentChange(pageNum) {
      roleinfo(pageNum).then(({ data }) => {
        this.total = data.page.total
        this.pageSize = data.page.size
        this.tableData = data.page.records
      })
    },
    handleClose() {
      // 关闭弹窗
      this.dialogVisible = false
      this.ImportDialog = false
      this.ExportDialog = false
      this.$refs.form.clearValidate()
    },
    cancel() {
      this.handleClose()
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 后续对表单的处理
          if (this.modalType === 0) {
            add(this.form).then(({ data }) => {
              // 重新获取列表的接口
              this.getData()
              // 跳转到最后一页查看最新添加的记录
              this.currentPage = data.page.pages
            })
          } else {
            update(this.form).then(() => {
              // 重新获取当前页列表的接口
              this.handleCurrentChange(this.currentPage)
            })
          }
          // 关闭弹窗
          this.dialogVisible = false
        }
      })
    },
    handleImport() {
      this.ImportDialog = true
    },
    handleExport() {
      this.ExportDialog = true
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handlemessage() {
      this.$message({
        type: 'success',
        message: '已成功上传文件'
      })
    }, handleExport1() {
      axios({ // 用axios发送get请求
        method: 'get',
        url: process.env.VUE_APP_BASE_API + '/RoleManage/export', // 请求地址
        responseType: 'blob', // 表明返回服务器返回的数据类型
        headers: {
          'Content-Type': 'application/json',
          'getResponse': 'true'
        }
      }).then(res => { // 处理返回的文件流
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

        const disposition = res.headers['content-disposition']
        const filename = disposition.split(/filename=/i).pop()
        const fileName = decodeURI(filename)

        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL对象
        document.body.removeChild(elink)
      })
    },
    handleExport2() {
      axios({ // 用axios发送get请求
        method: 'get',
        url: process.env.VUE_APP_BASE_API + '/RoleManage/extemplate', // 请求地址
        responseType: 'blob', // 表明返回服务器返回的数据类型
        headers: {
          'Content-Type': 'application/json',
          'getResponse': 'true'
        }
      }).then(res => { // 处理返回的文件流
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

        const disposition = res.headers['content-disposition']
        const filename = disposition.split(/filename=/i).pop()
        const fileName = decodeURI(filename)

        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL对象
        document.body.removeChild(elink)
      })
    }
  }
}
</script>

<style>
.app-container {
  margin: 0 auto;
}
</style>
